<?php

namespace app\db\index;

class D_singlePage
{

    /**
     * 信息格式化
     */
    protected function detailed($Result, $format)
    {
        // 更新时间
        if (isset($Result['updateTime'])) {
            $Result['updateTimeFormat'] = app("yifangTime")::getDateTime('Y-m-d H:i:s', $Result['updateTime']);
        }
        if (isset($Result['linkUrl'])) {  //存放文件名和路径
            $Result['path'] = dirname($Result['linkUrl']);
            if ($Result['path']) {
                $Result['path'] .= "/";
            }

            $Result['file'] = basename($Result['linkUrl']);

        }
        if (isset($Result['isLink'])) {
            if ($Result['isLink']) {
                $Result["linkUrl"] = $Result['linkUrl'];
            } else {
                //判断显示域名,用户是否填写了,域名, 如果没填写,使用系统域名
                $Result["linkUrl"] = ($Result['domain']==""?config("app.url"):$Result['domain'] ) . $Result['linkUrl'];
                //判断是否有变量,如果有直接替换,列表页和标签会用到
                if (strpos( $Result["linkUrl"],"{id}")!==false){
                    $Result["linkUrl"]=str_replace("{id}",$Result["id"],$Result["linkUrl"]);
                }
            }
        }


        if (isset($Result['style'])) {
            $Result['color'] = str_getBetween($Result['style'] . ";", "color:", ";");
        }
        // 内容
        if (isset($Result['content'])) {
            $Result['contentFormat'] = dhtmlspecialcharsDecode($Result['content']);
        }
        // 返回结果
        return $Result;
    }

    /**
     * 获取所有单页列表
     * @params string 0 field
     * @param string $paramObj
     */
    public function getList($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = array();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                "field" => "",
                "format" => "",
            );
            $dataDefault = array();
            $dataDefault["field"] = "id,item,level,title,style,seoTitle,seoKeywords,seoDescription,updateTime,sort,hits,isLink,linkUrl,domain,template";
            $dataDefault["format"] = "1";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();

            try {
                $result = Db()->name(app("cmsTable")::single_page())->order("sort")->field($dataObj->request->field)->where($condition)->select();
                if ($result ) {
                    foreach ($result as $key => $val) {
                        if ($dataObj->request->format) {
                            $result[$key] = $this->detailed($val, $dataObj->request->format);
                        }
                    }
                }
                $final_arr["result"] = $result;


            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    public function __call($name, $arguments)
    {
        return recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::UNDEFINED_METHOD, lang("sys.noMethodDefined"), $name, $arguments);
    }

    /**
     * 获取单页详细信息
     * @param string $paramObj
     */
    public function info($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require|number',
                'field' => '',
                'format' => '',
                'verify' => '',
            );
            $dataDefault = array();
            $dataDefault["field"] = "*";


            $dataDefault["verify"] = "1";
            $dataDefault["format"] = "1";
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $condition = array();
            $condition[] = array(
                "id", "=", $dataObj->request->id
            );
            try {
                $result = Db()->name(app("cmsTable")::single_page())->field($dataObj->request->field)->where($condition)->find();
                if ($dataObj->request->verify) {
                    if (empty($result)) {
                        $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::DATA_NOT_EXIST, lang("sys.dataNotExists"));
                    }
                }
                if ($dataObj->request->format) {
                    $result = $this->detailed($result, $dataObj->request->format);
                }

                $final_arr["result"] = $result;
            } catch (\Throwable $e) {
                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
            }
        }
        return $final_arr;
    }

    /**
     * 更新点击量
     * @param string $paramObj
     */
    public function upHits($paramObj = "")
    {
        $dataObj = paramsObj();
        $dataObj->request = paramsObj();
        $dataObj->data = paramsObj();
        $dataObj->data->use_trans = false;
        $dataObj->result = new \ArrayObject();

        $final_arr = logInit();
        if ($final_arr["error_no"] == 0) {
            $mixed = parseToArr($paramObj, "mixed", 0);
            $params = parseToArr($paramObj, "params", array());
            $messages = parseToArr($paramObj, "messages", array());
            $rules = array(
                'id' => 'require',
            );
            $dataDefault = array();
            $paramsObj = paramsObj();
            $paramsObj->params = $params;
            $paramsObj->mixed = $mixed;
            $paramsObj->rules = $rules;
            $paramsObj->messages = $messages;
            $paramsObj->dataDefault = $dataDefault;
            $checkResult = app("verifyParam")::validatorRequest($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $dataObj->request = $checkResult["result"];
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        if ($final_arr["error_no"] == 0) {
            $paramsObj = paramsObj();
            $paramsObj->params = array(
                "id" => $dataObj->request->id,
            );
            $checkResult = $this->info($paramsObj);
            if ($checkResult["error_no"] == 0) {
                $infoData=$checkResult["result"];
                if($infoData){
                    if ($final_arr["error_no"] == 0) {
                        $condition = array();
                        $condition[] = array(
                            "id", "=", $infoData["id"]
                        );
                        $data=array();
                        $data["hits"]=Db()->raw("hits+1") ;
                        if ($data) {
                            try {
                                $result = Db()->name(app("cmsTable")::single_page())->where($condition)->data($data)->update();
                                if($result["affected_rows"] >= "0"){
                                    $return = array();
                                    $return["id"] = $dataObj->request->id;
                                    $return["affected_rows"] = $result["affected_rows"];
                                    $final_arr["result"] =$return;
                                }else{
                                    $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_WARNING, app("errorCode")::OP_FAIL, lang("sys.opFail"));
                                }
                            } catch (\Throwable $e) {
                                $final_arr = recordLogMsgLevelTwo(app("errorLevel")::E_ERROR, app("errorCode")::SQL_ERROR, lang("sys.error"), $e->getMessage());
                            }
                        } else {
                            $return = array();
                            $return["id"] = $dataObj->request->id;
                            $return["affected_rows"] = 0;
                            $final_arr["result"] = $return;
                        }
                    }
                }
            } else {
                $final_arr = logCallErrorMsg($final_arr, $checkResult);
            }
        }
        return $final_arr;
    }
}